package com.qili.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qili.annotation.TokenCheck;
import com.qili.base.entity.CurrentUser;
import com.qili.redis.RedisService;
import com.qili.util.StringUtil;
import lombok.extern.log4j.Log4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zhaoyongke
 * @date 2021/11/19
 * @description
 */
@Log4j
public class Authnterceptor  implements HandlerInterceptor {
    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        log.info("---拦截器进入---");
        String requestURI = request.getRequestURI();
        log.info("---拦截器进入---"+requestURI);
        String token = request.getHeader("token");
        HandlerMethod handlermethod=(HandlerMethod)o;
        Method method = handlermethod.getMethod();
        if(method.isAnnotationPresent(TokenCheck.class)){
            TokenCheck annotation = method.getAnnotation(TokenCheck.class);
            if(annotation.required()){
                log.info("---token 校验---");
                System.out.println("=========================================");
                if(StringUtil.isBlank(token)){
                    throw   new  Exception("token为空");
                }
                String s = redisService.get("token_"+token);
                if(StringUtil.isBlank(s)){
                    throw   new  Exception("token过期了");
                }
                // 校验token
                try {
                    DecodedJWT jwt = JWT.decode(token);
                } catch (Exception  e) {
                    throw   new  Exception("token出错了");
                }
                return  true;
            }
        }
        if(StringUtil.isNotBlank(token)){
            redisService.set("token_"+token,token,172800l);
        }
        return  true;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {


    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        log.info("---afterCompletion---");
    }
}
